//
//  PCDApiNavigateBackMiniProgram.m
//  PCDBank
//
//  Created by DK on 2021/2/25.
//  Copyright © 2021 DK. All rights reserved.
//

#import "PCDApiNavigateBackMiniProgram.h"
#import "PCDBankWebViewController.h"
#import "PCDDataBaseModel.h"

@implementation PCDApiNavigateBackMiniProgram

- (void)handler:(id)data andContext:(PCDContext *)context ResponseCallback:(WVJBResponseCallback )responseCallback
{

    NSDictionary *tempDic = (NSDictionary *)data;
    NSString *callBack = [tempDic objectForKey:@"success"];
    NSString *strUrl = [tempDic objectForKey:@"url"];
    NSString *extraData =[tempDic objectForKey:@"extraData"];
    [PCDDataBaseModel shareModel].extraData = extraData;
    
    NSMutableArray *viewCtrs = [self clearViews];
    
    [PCDPageViewMangeGet().baseNavgatView setViewControllers:viewCtrs animated:NO];
    
    
    if (![PCDUtil nilOrEmptyString:callBack]) {
        //
        evaluateJavaScriptOnMainThread(self,callBack,@"");
    }
}

-(NSMutableArray *)clearViews
{
    NSMutableArray *viewCtrs = [NSMutableArray arrayWithArray:PCDPageViewMangeGet().baseNavgatView.viewControllers];
    
    NSInteger i =viewCtrs.count-1;
    while (i>=0) {
        
        id view = [viewCtrs objectAtIndex:i];
        
        if ([view isKindOfClass:[PCDBankWebViewController class]]) {
            
            PCDBankWebViewController *viewPage = (PCDBankWebViewController *)view;
            NSString *strAppId = viewPage.appId;
            if ([PCDPageViewMangeGet().appId isEqual:strAppId]) {
                [viewCtrs removeObjectAtIndex:i];
            }else{
                
                if (PCDPageViewMangeGet().baseUrlList.count >1) {
                    [PCDPageViewMangeGet().baseUrlList removeLastObject];
                }
                
                PCDPageViewMangeGet().appId = strAppId;
                PCDPageViewMangeGet().baseUrl = [PCDPageViewMangeGet().baseUrlList lastObject];
                
                break;
            }
            i--;
        }else{
            break;
        }
    }
    return viewCtrs;
}

@end
